package com.xyyl.patient.service.user;

import com.google.common.collect.Lists;
import com.xyyl.patient.core.constant.AppEnum;
import com.xyyl.patient.core.support.Pager;
import com.xyyl.patient.core.util.Distance;
import com.xyyl.patient.core.util.StringUtils;
import com.xyyl.patient.entity.doctor.Doctor;
import com.xyyl.patient.entity.doctor.DoctorPatientRelation;
import com.xyyl.patient.entity.order.ConsultOrder;
import com.xyyl.patient.entity.pharmacy.Pharmacy;
import com.xyyl.patient.entity.question.Prescription;
import com.xyyl.patient.entity.user.AccountRecord;
import com.xyyl.patient.entity.user.User;
import com.xyyl.patient.mapper.Pharmacy.PharmacyMapper;
import com.xyyl.patient.mapper.doctor.DoctorPatientRelationMapper;
import com.xyyl.patient.mapper.order.ConsultOrderMapper;
import com.xyyl.patient.mapper.question.PrescriptionMapper;
import com.xyyl.patient.mapper.user.AccountRecordMapper;
import com.xyyl.patient.mapper.user.UserMapper;
import com.xyyl.patient.vo.IMVo;
import com.xyyl.patient.vo.user.UserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

/**
 * @author chens
 * @ClassName: UserServiceImp
 * @Description: 患者信息Service
 * @date 2017年8月17日
 */
@Service("userService")
public class UserServiceImp implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AccountRecordMapper accountRecordMapper;

    @Autowired
    private DoctorPatientRelationMapper doctorPatientRelationMapper;

    @Autowired
    private PrescriptionMapper prescriptionMapper;

    @Autowired
    private PharmacyMapper pharmacyMapper;

    @Autowired
    private ConsultOrderMapper consultOrderMapper;

    @Override
    public List<UserVo> selectList(Pager pager) {

        List<UserVo> userVos = Lists.newArrayList();

        List<User> users = userMapper.queryForPage(pager);

        if (users != null && !users.isEmpty()) {
            UserVo userVo = null;
            for (User user : users) {
                userVo = new UserVo();
                BeanUtils.copyProperties(user, userVo);

                userVo.setSex(AppEnum.SexEnum.getName(user.getSex()));

                userVos.add(userVo);
            }

            pager.setData(userVos);
        }
        return userVos;
    }

    @Override
    public UserVo queryUserDetailById(Integer userid) {

        UserVo userVo = null;
        User user = userMapper.queryUserByOption(userid, null);

        if (user != null) {
            userVo = new UserVo();

            BeanUtils.copyProperties(user, userVo);
            userVo.setSex(AppEnum.SexEnum.getName(user.getSex()));
        }
        return userVo;
    }

    /**
     * 绑定用户信息
     */
    @Override
    public int bindUserInfo(User user) {
        // 根据openid获取用户明细
        User userVo = userMapper.queryUserByOption(null, user.getOpenid());
        if (userVo != null) {
            user.setId(userVo.getId());
            userMapper.update(user);
        } else {
            user.setAllpoints(0);
            userMapper.insert(user);
        }
        return user.getId();
    }

    @Override
    public List<IMVo> getIndexIM(Integer userid) {
        List<IMVo> userVos = Lists.newArrayList();
        List<IMVo> imVoList = userMapper.getIndexIM(userid);
        if (imVoList != null && !imVoList.isEmpty()) {
            IMVo imVo = null;
            for (IMVo imVo1 : imVoList) {
                imVo = new IMVo();
                BeanUtils.copyProperties(imVo1, imVo);
                imVo.setSex(AppEnum.SexEnum.getName(Integer.valueOf(imVo1.getSex())));
                imVo.setReplyTime(imVo1.getReplyTime() != null ? "医生已回复" : "医生待回复");
                imVo.setCreatetime(imVo1.getCreatetime().substring(5, 10).replaceAll("-", "月") + "日");
                if (StringUtils.isEmpty(imVo1.getDocAvatar())) {
                    imVo.setDocAvatar("http://xinyuyl.oss-cn-beijing.aliyuncs.com/app/doctor/docture.png");
                }
                try {
                    imVo.setNickname(URLDecoder.decode(imVo1.getNickname(), "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                userVos.add(imVo);
            }
        }
        return userVos;
    }

    public List<AccountRecord> queryUserAccountRecoreList(Pager pager) {
        return accountRecordMapper.queryForPage(pager);
    }

    /*
     * 查询用户医生列表
     */
    @Override
    public List<Doctor> queryUserDoctorList(Integer patient) {
        return doctorPatientRelationMapper.selectDoctorByPatientid(patient);
    }

    @Override
    public List<Prescription> queryUserPrescriptionList(Integer patientid) {
        return prescriptionMapper.queryPrescription(patientid);
    }

    @Override
    public Integer setRelation(DoctorPatientRelation doctorPatientRelation) {
        return doctorPatientRelationMapper.update(doctorPatientRelation);
    }

    @Override
    public Prescription queryUserPrescription(Integer id) {

        Prescription prescription = prescriptionMapper.queryPrescriptionOne(id);
        if (prescription != null) {
            ConsultOrder consultOrder = consultOrderMapper.selectOneBysnid(prescription.getOrdersn());
            if (consultOrder != null) {
                prescription.setPrescriptionPrice(consultOrder.getPayamount());
            }
        }

        return prescription;
    }

    /* 查最近的药店 */
    @Override
    public List<Pharmacy> getBestPharmacy(double la, double lo) {
        List<Pharmacy> pharmacyList = pharmacyMapper.selectList(new Pharmacy());
        List<Pharmacy> pharmacyList1 = new ArrayList<>();
        if (pharmacyList.size() > 0) {

            TreeMap<Double,Integer> treeMap = new TreeMap();
            pharmacyList.forEach(pharmacy -> {
                int key = pharmacy.getId().intValue();
                Double juli = Distance.getDistance(la, lo, Double.parseDouble(pharmacy.getLat()),
                        Double.parseDouble(pharmacy.getLon()));
                treeMap.put(juli, key);
            });
            Set<Map.Entry<Double, Integer>> entry = treeMap.entrySet();
            for(Iterator<Map.Entry<Double,Integer>> it = entry.iterator(); it.hasNext();) {
                Map.Entry<Double, Integer> entry2 = it.next();
                Pharmacy pharmacy = pharmacyMapper.selectOne(entry2.getValue());
                pharmacy.setJuli(entry2.getKey().toString());
                pharmacyList1.add(pharmacy);
            }
        }
        return pharmacyList1;

    }

}
